package com.dhcc.DRGsHosp.web.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;

import org.openkoala.koala.commons.InvokeResult;
import org.openkoala.security.shiro.CurrentUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ContextLoader;

import com.dhcc.DRGsHosp.facade.DrgsIndexCalFacade;
import com.dhcc.DRGsHosp.facade.JasperReportFacade;
import com.dhcc.DRGsHosp.facade.MDCGroupFacade;
import com.dhcc.DRGsHosp.facade.QuotaManageFacade;
import com.dhcc.DRGsHosp.facade.dto.MDCGroupDTO;
import com.dhcc.DRGsHosp.infra.util.GlobalData;
import com.dhcc.DRGsHosp.infra.util.MonitorResultUtil;
import net.sf.jasperreports.engine.JRAbstractExporter;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.HtmlExporter;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.ooxml.JRDocxExporter;
import net.sf.jasperreports.engine.export.ooxml.JRPptxExporter;
import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.export.ExporterInput;
import net.sf.jasperreports.export.HtmlExporterOutput;
import net.sf.jasperreports.export.OutputStreamExporterOutput;
import net.sf.jasperreports.export.SimpleExporterInput;
import net.sf.jasperreports.export.SimpleHtmlExporterOutput;
import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput;
/**
 * 
 * @title		:ReportController.java
 * @description	:返回报表视图
 * @author		:Sulina
 * @date		:2016年12月28日
 * @version     :1.0
 * @copyright   :DHCC 2013-2014
 */
@Controller("drgsHospWebController38")
@RequestMapping("/Report")
public class ReportController {
	@Autowired
	private DrgsIndexCalFacade drgsIndexCalFacade ;
	@Autowired
	private JasperReportFacade jasperReportFacade ;
	@Autowired
	private QuotaManageFacade quotaManageFacade ;
	@Autowired
	private MDCGroupFacade mDCGroupFacade ;
	
	/**
	 *  文件预览和导出的POST方法
	 *  exreportPMode.  
	 *  @Description：
	 *  @Author ChenHanlin
	 *  @param response 
	 *  @param param 查询参数
	 *  @param reportType
	 *  @param reportId
	 *  @Date:2018年1月31日下午2:37:29
	 */
	@RequestMapping(value = "/exreportPMode", method = RequestMethod.POST)
	public void exreportPMode(HttpServletResponse response,@RequestParam String param,@RequestParam String reportType,@RequestParam String reportId) {
		//对服务器响应进行按照uft-8编码
		response.setCharacterEncoding("UTF-8") ;
		// 1 获取报表的配置信息 路径和文件名
		List<Map<String, Object>> reportList = new ArrayList<>() ;
		reportList = jasperReportFacade.findJasperReport(reportId) ;
	    String roleName = CurrentUser.getRoleName() ;
	    // 2 参数处理
		jasperReportFacade.processQueryParam(reportList,param,reportType,roleName) ;
		// 3  报表填充
	    List<JasperPrint> jasperPrintList = new ArrayList<>();
		try {
			jasperPrintList = jasperReportFacade.getJasperPrint(reportList);
		} catch (IOException e) {
			e.printStackTrace();
		}
	    // 4.报表导出
	    JRAbstractExporter<?, ?, OutputStreamExporterOutput, ?>  exporter = null ;
	    String contentType = null ;
	    	switch(reportType) {
		    case "html" :
		    	contentType = "text/html" ; 
		    	break ;
	    	case "pdf" :
		    	exporter = new  JRPdfExporter(); 
		    	contentType = "application/pdf" ; 
		    	break ;
		    case "xlsx" :
		    	exporter = new JRXlsxExporter(); 
		    	contentType = "application/vnd.ms-excel" ; 
		    	break ;
		    case "docx" :
		    	exporter = new JRDocxExporter() ; 
		    	contentType = "application/msword" ; 
		    	break ;
		    case "pptx" :
		    	exporter = new JRPptxExporter(); 
		    	contentType = "application/ms-powerpoint" ; 
		    	break ; 
		    default :  
		    	contentType = "text/html" ; 
		    	break ;
	    }
	    // JRHtmlExporter 已过时
	    if("html".equals(reportType)) {
	    	HtmlExporter htmlExporter = new HtmlExporter() ;
	    	// 设置输入项  
	        ExporterInput exporterInput = new SimpleExporterInput(jasperPrintList.get(0)); 
	        htmlExporter.setExporterInput(exporterInput) ;
	        // 设置输出项 
	        response.setContentType(contentType);  
	        HtmlExporterOutput exporterOutput = null ;
			try {
				response.setHeader("Content-disposition", "inline; filename="  
					+ URLEncoder.encode( reportList.get(0).get("fileName")+"" ,"utf8"));
				 exporterOutput = new SimpleHtmlExporterOutput(response.getOutputStream());
					htmlExporter.setExporterOutput(exporterOutput);
			        htmlExporter.exportReport();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (JRException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if(exporterOutput != null) {
					exporterOutput.close() ;
				}
			}
	    } else {
	    	 // 设置输入项  
	        exporter.setExporterInput(SimpleExporterInput.getInstance(jasperPrintList));
	        // 设置输出项  
	        response.setContentType(contentType); 
	        OutputStreamExporterOutput exporterOutput = null ;
        	try {
				response.setHeader("Content-disposition", "attachment; filename="  
				        + URLEncoder.encode(reportList.get(0).get("fileName")+"."+reportType ,"utf8"));
				exporterOutput = new SimpleOutputStreamExporterOutput(
			                response.getOutputStream()); 
			        exporter.setExporterOutput(exporterOutput); 
			        exporter.exportReport();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (JRException e) {
				e.printStackTrace();
			} finally {
				if(exporterOutput != null){
					exporterOutput.close() ;
				}
			}
	    }
	}
	
	/**
	 * 
	 *  使用datatable 预览数据
	 *  previewInDatatable.  
	 *  @Description：
	 *  @Author ChenHanlin
	 *  @param param
	 *  @param reportId
	 *  @return
	 *  @Date:2017年9月5日上午9:42:33
	 */
	@ResponseBody
	@RequestMapping(value = "/previewInDatatable", method = RequestMethod.POST)
	public InvokeResult previewInDatatable(@RequestParam String param,@RequestParam String reportId) {
	    ServletContext servletContext = ContextLoader.getCurrentWebApplicationContext().getServletContext() ;
	    // 1 获取报表的配置信息 路径和文件名
 		List<Map<String, Object>> reportList = new ArrayList<>() ;
 		reportList = jasperReportFacade.findJasperReport(reportId) ;
 	    String roleName = CurrentUser.getRoleName() ;
 	    // 2 参数处理
 		jasperReportFacade.processQueryParam(reportList,param,null,roleName) ;
 		InputStream jasperStream  = null ;
 		JasperReport jasperReport = null ;
 		try {
 			 jasperStream =  servletContext.getResourceAsStream(reportList.get(0).get("path")+"") ;
 			 // 获取jasper模板文件里的SQL
 			 jasperReport = (JasperReport) JRLoader.loadObject(jasperStream);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(null!=jasperStream){
				try {
					jasperStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	  
		String sql = null ;
		if(null!=jasperReport){
			sql = jasperReport.getQuery().getText() ;
		}
		List<Map<String,Object>> resultList = new ArrayList<>() ;
		if(null!=sql){
			resultList = jasperReportFacade.getJasperResult(sql,(Map<String,Object>)reportList.get(0).get("params")) ;
		}
		
		Map<String,Object> resultMap = new HashMap<>() ;
		// 获取全部病例明细 子模板数据 
		if("caseDayAnalysisAll".equals(reportId)) {
			InputStream jasperStreamCaseAll = null ;
			JasperReport jasperReportCaseAll = null ;
			try {
				jasperStreamCaseAll =  servletContext.getResourceAsStream("/WEB-INF/jasper/yizheng/caseAllson.jasper") ;
				jasperReportCaseAll = (JasperReport) JRLoader.loadObject(jasperStreamCaseAll);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if(null!=jasperStreamCaseAll){
					try {
						jasperStreamCaseAll.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			String sqlCaseAll = null ;
			if(null!=jasperReportCaseAll){
				sqlCaseAll = jasperReportCaseAll.getQuery().getText() ;
			}
			List<Map<String,Object>> resultListCaseAll = new ArrayList<>() ;
			if(null!=sqlCaseAll){
				resultListCaseAll = jasperReportFacade.getJasperResult(sqlCaseAll,(Map<String,Object>)reportList.get(0).get("params")) ;
			}
			resultMap.put("total", resultList) ;
			resultMap.put("detail", resultListCaseAll) ;
			return InvokeResult.success(resultMap);
		}
		resultMap.put("detail", resultList) ;
		return InvokeResult.success(resultMap);
	}
	
	/**
	 *  获取报表初始化时间
	 *  initeDateTimePicker.  
	 *  @Description：
	 *  @Author ChenHanlin
	 *  @return 
	 *  @Date:2017年9月4日下午7:11:44
	 */
	@ResponseBody
	@RequestMapping(value = "/initeDateTimePicker", method = RequestMethod.POST)
	public InvokeResult initeDateTimePicker() {
		String lastDate = drgsIndexCalFacade.getLatestDate() ;
		String lastMonth = lastDate.substring(0, 7) ;
		String startDateMonth = MonitorResultUtil.getStartDateMonth(lastMonth) ;
		String endDateMonth = MonitorResultUtil.getEndDateMonth(lastMonth) ;
		Map<String,Object> map = new HashMap<String, Object>() ;
		map.put("lastDate", lastDate) ;
		map.put("startDateMonth", startDateMonth) ;
		map.put("endDateMonth", endDateMonth) ;
		return InvokeResult.success(map);
	}
	
	/**
	 *  获取所有外院比较对象
	 *  getOtherHspManage.  
	 *  @Description：
	 *  @Author ChenHanlin
	 *  @return 
	 *  @Date:2017年9月1日下午7:11:44
	 */
	@ResponseBody
	@RequestMapping(value = "/getOtherHspManage", method = RequestMethod.POST)
	public InvokeResult getOtherHspManage() {
		List<Map<String,Object>> list = quotaManageFacade.findQuotaManageByparMsCode("std_out") ;
		return InvokeResult.success(list);
	}
	
	/**
	 *  获取所有某类标杆的所有年份
	 *  getOtherHspManageYears.  
	 *  @Description：
	 *  @Author ChenHanlin
	 *  @param parMsCode 标杆类型
	 *  @return 
	 *  @Date:2017年9月16日
	 */
	@ResponseBody
	@RequestMapping(value = "/getOtherHspManageYears", method = RequestMethod.POST)
	public InvokeResult getOtherHspManageYears(String parMsCode) {
		List<String> list = quotaManageFacade.getOtherHspManageYears(parMsCode) ;
		return InvokeResult.success(list);
	}
	
	
	/**
	 *  获取科室组 科室层 病区数据
	 *  queryDepTree.  
	 *  @Description：
	 *  @Author ChenHanlin
	 *  @param chkStyle 选择框类型： 单选/多选
	 *  @param layer 层级：科室、病区
	 *  @return 
	 *  @Date:2017年11月7日上午8:45:39
	 */
	@ResponseBody
	@RequestMapping(value = "/queryDepTree", method = RequestMethod.POST)
	public InvokeResult queryDepTree(String chkStyle,String layer) {
		List<Map<String, Object>> list = jasperReportFacade.queryDepTree(chkStyle,layer) ;
		return InvokeResult.success(list);
	}

	
	@ResponseBody
	@RequestMapping(value = "/findAllMDC", method = RequestMethod.POST)
	public InvokeResult findAllMDC() {
		String verCode = GlobalData.sysConfig.get("GROUP_VER");
		MDCGroupDTO mdcDto = new MDCGroupDTO();
		if(verCode==null) {
			InvokeResult.failure("没有查询到配置信息") ;
		} 
		mdcDto.setVerCode(verCode);
		List<Map<String, Object>> mdcList = mDCGroupFacade.findAllMDC(mdcDto ) ;
		return InvokeResult.success(mdcList);
	}
	
	
	
}
